﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using BlogApp.Data.Service;
using BlogApp.WP8.Resources;
using BlogApp.WP8.Utils;
using GalaSoft.MvvmLight.Command;
using Microsoft.Practices.ServiceLocation;
using Newtonsoft.Json;

namespace BlogApp.WP8.ViewModel
{
    public class CommentViewModel : DataViewModel
    {

        private bool _success;
        public bool Success
        {
            get { return _success; }
            set { _success = value; RaisePropertyChanged("Success"); }
        }


        private string _userName;

        public string UserName
        {
            get { return _userName; }
            set { _userName = value; RaisePropertyChanged("UserName"); }
        }

        private string _mailAdress;

        public string MailAdress
        {
            get { return _mailAdress; }
            set { _mailAdress = value; RaisePropertyChanged("MailAdress"); }
        }

        private string _comment;

        public string Comment
        {
            get { return _comment; }
            set { _comment = value; RaisePropertyChanged("Comment"); }
        }


        public RelayCommand<string> CheckEmailCommand { get; set; }
        public RelayCommand<List<String>> CheckNullOrEmpty { get; set; }
        public RelayCommand<string> PostCommentToBlogPost { get; set; }

        public CommentViewModel()
        {
            PostCommentToBlogPost = new RelayCommand<string>(postCommentToBlogPost);
        }

        private async void postCommentToBlogPost(string blogId)
        {
            if (!DataService.Instance.IsOffline)
            {
                try
                {
                    var result = await DataService.Instance.SubmitCommentAsync(blogId, UserName, MailAdress, Comment);
                    if (result != null)
                    {
                        Success = true;

                        var comment = await JsonConvert.SerializeObjectAsync(result);

                        ServiceLocator.Current.GetInstance<PostViewModel>().SelectedBlogPost.Comments.Add(comment);

                        return;
                    }

                    Success = false;

                    //MessageBox.Show(Success ? AppResources.CommentSentSuccess : AppResources.CommentSentFail, string.Empty, MessageBoxButton.OK);
                }
                catch (Exception)
                {
                    Debug.WriteLine("CommentViewModel.cs | postCommentToBlogPost | Error with submit comment");
                }
            }
            else
            {
                MessageBox.Show(AppResources.CommentSentFail);
            }
        }
    }
}
